import { defineStore } from 'pinia';
import { TOKEN_NAME } from '@/config/global';
import { store, usePermissionStore } from '@/store';
import { getUser } from '@/api/login/login';
import { curatorlogin } from '@/api/user/user';
import { removeAuthorization, getHeardToken, getHeardXtoken } from '@/api/utils';

const InitUserInfo = {
  info: {},
  roles: ['all'],
};

export const useUserStore = defineStore('user', {
  state: () => ({
    curator: {},
    roleLevel: 3,
    userLevel: 0,
    VipLevel: 0, //vip等级
    vipInfo: {
      companyId: 0,
      name: '',
      logoUrl: '',
      authType: 0,
      level: 0,
      total: 0,
      auditing: 0,
      role: 0,
      coverUrl: '',
      endTime: '',
      startTime: '',
    },
    imgConcat: 'http://101.34.143.36:8890/api/image/',
    token: localStorage.getItem(TOKEN_NAME) || 'main_token', // 默认token不走权限
    userInfo: { ...InitUserInfo },
  }),
  getters: {
    roles: (state) => {
      return state.userInfo?.roles;
    },
  },
  actions: { 
    setVipLevel(e: number) {
      //vip等级设置
      this.VipLevel = e ? e : 0;
    },
    setuserLevel(userInfo: number): void {
      this.userLevel = userInfo;
    },
    setroleLevel(userInfo?: number): void {
      this.roleLevel = userInfo ? userInfo : 3;
    },
    async getUserInfo() {
      try {
        const res = await getUser();
        if (res.statusCode !== 200) {
          this.userInfo = { info: null, roles: ['all'] };
          return;
        }

        this.token = getHeardToken();
        this.userInfo = {
          info: res.data,
          roles: ['all'],
        };
        // this.vipInfo=res.data.companys; 
        // console.log(res.data,'coy')
        this.userLevel = res.data.type;  
         
          let curator = await curatorlogin();
          this.setroleLevel(curator.data.companys[0]?.role)
          
          //role==1 管理员  rple===2 策展人
          if (curator.data && res.data.type === 2) {
            this.curator = curator.data.companys[0];
            this.vipInfo=curator.data.companys[0];
          }else {
            this.curator = {};
            this.vipInfo=curator.data?.companys[0];
          }
          if (this.userLevel) {
            this.setuserLevel(2);
          } else {
            this.setuserLevel(0);
          }
         
      } catch(err) {
        console.log(err,'coy')
      }
    },
    reoveInfo() {
      removeAuthorization();
      this.userInfo = { ...InitUserInfo };
    },
    async logout() {
      removeAuthorization();
      this.token = '';
      this.userInfo = { info: null, roles: ['all'] };
    },
    async removeToken() {
      this.token = '';
      removeAuthorization();
    },
  },
  persist: {
    afterRestore: (ctx) => {
      if (ctx.store.roles && ctx.store.roles.length > 0) {
        const permissionStore = usePermissionStore();
        permissionStore.initRoutes(ctx.store.roles);
      }
    },
  },
});

export function getUserStore() {
  return useUserStore(store);
}
